// pages/order/order.js
const app =getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgurl:app.globalData.Imageurl,
    consigneeName:'',
    consigneeMobile:'',
    consigneeAddress:'',
    isaddshow:true,
    isaddshowto:false,
    trafficCost:0,
    beizu:'',
    couponId:'',
    couponAmount:'',
    iscoupon:2,
    ispaycg:false,
    total:0,
    goodsId:"",
     
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var sjs=this.randomWord()
    var datatime = Date.parse(new Date());
    var tokens=''+sjs+''+datatime+''+app.globalData.userId
    this.getConsigneeInfo()
    console.log(options)
    if(options.type==1){
      console.log('类型购物车购买')
      var goods=JSON.parse(options.shoplist)
      var goodsId=[]
      goods.forEach((item,index)=>{
        goodsId.push(item.goodsId)
      })
      this.setData({
        goodsSpecs:goods,
        total:options.carttotal*1,
        token:tokens,
        type:1,
        goodsId:goodsId,
      })

    }else{
      console.log('类型立即购买')
      console.log(JSON.parse(options.goodsSpec))
      var goods=JSON.parse(options.goodsSpec)
      this.setData({
        goodsSpecs:goods,
        goodsNumber:options.goodsNumber,
        total:goods.specPrice*options.goodsNumber,
        token:tokens,
        type:2,
        goodsId:options.goodsId,
      })
   }
   this.getCoupon()
  },
  //去订单
  goorder(){
    console.log('sdsad')
    wx.navigateTo({
      url: '/pages/order/order?showtype=1',
    })
  },
  //回到上一页
  godetails(){
    wx.navigateBack({
      delta: 1,
    })
  },
  bindblur(e){
    this.setData({
      beizu:e.detail.value
    })
  },
  bindconfirm(e){
    this.setData({
      beizu:e.detail.value
    })
  },
  setaddress(){
    wx.navigateTo({
      url: '/pages/addressmg/addressmg?addtype=1',
    })
  },
  //生成随机数
  randomWord() {
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
     var nums = "";
      for (var i = 0; i < 20; i++) {
      var id = parseInt(Math.random() * 61);
      nums += chars[id]
      }
      return nums; 
      },
    //立即支付
  gopay(){
    console.log('2w')
    var t = this;
    if (this.data.consigneeName!=''&& this.data.consigneeMobile!=''&& this.data.consigneeAddress!='') {
      console.log('2q')
      wx.request({
        url: app.globalData.Interfaceurl + 'saveBuyPreOrder',
        method:'POST',
        header: {
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        data:{
            userId:app.globalData.userId,
            goodsSpecId:t.data.goodsSpecs.id,
            goodsNumber:t.data.goodsNumber,
            token:t.data.token,
            orderRemarks:t.data.beizu,
            couponId:t.data.couponId,
            consigneeName:t.data.consigneeName,
            consigneeMobile:t.data.consigneeMobile,
            consigneeAddress:t.data.consigneeAddress,
            trafficCost:t.data.trafficCost,
        },
        success(res){
          if(res.data.result=='0'){
            wx.requestPayment({
              timeStamp: res.data.dataInfo.timeStamp,
              nonceStr: res.data.dataInfo.nonceStr,
              package: res.data.dataInfo.package,
              signType: res.data.dataInfo.signType,
              paySign: res.data.dataInfo.sign,
              success(res) { 
                console.log(res)
                  t.setData({
                    ispaycg:true
                  })
              },
              fail(res) {
                  console.log(res)
                  wx.redirectTo({
                    url: '/pages/order/order?showtype=2',
                })
              }
           })

          }else{
            wx.showToast({
              title: res.data.message,
              icon:'none'
            })
          }
            
        }
    })
 
    }else{
      wx.showToast({
        title: '请选择收货地址',
        icon:'none'
      })
    }
  },
  //获取使用的优惠券
  gocoupon(){
    //立即购买优惠券
    // 
    if(this.data.type==2 ){
      wx.navigateTo({
        url: '/pages/coupon/coupon?use=1&orderamoun='+this.data.total+'&goodsId='+JSON.stringify(this.data.goodsId)+"&usetype="+1+'&iscoupon='+this.data.iscoupon,
      })
    }
//购物车优惠券
if(this.data.type==1 && this.data.iscoupon==1){
  let goodsId=JSON.stringify(this.data.goodsId)
  wx.navigateTo({
    url: '/pages/coupon/coupon?use=1&orderamoun='+this.data.total+'&goodsId='+goodsId+'&iscoupon='+this.data.iscoupon,
  })
}
if(this.data.type==1 && this.data.iscoupon==2){
  let goodsId=JSON.stringify(this.data.goodsId)
  wx.navigateTo({
    url: '/pages/coupon/coupon?use=1&orderamoun='+this.data.total+'&goodsId='+goodsId+'&iscoupon='+this.data.iscoupon,
  })
}
      
    
    
  },
  getCoupon(){
    var t=this
    console.log(t.data.total)
    wx.request({
      url: app.globalData.Interfaceurl + 'getMyCoupon',
      method: "post",
      header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
          userId: app.globalData.userId,
          couponState:2,
          orderAmount:t.data.total,
          // goodIds:t.data.goodsId
      },
      success: res => {
        console.log(res)
        if (res.data.couponList.length>0) {
          t.setData({
            iscoupon:1
          })
        }else{
          t.setData({
            iscoupon:2
          })
        }
      }

    })
  },
  //获取地址
  getConsigneeInfo(){
    var t=this
    wx.request({
      url: app.globalData.Interfaceurl + 'getConsigneeInfo',
      method: "post",
      header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
          userId: app.globalData.userId,
      },
      success: res => {
          console.log(res)
          if (res.data.consigneeInfoList.length>0) {
            if (res.data.consigneeInfoList[0].defaultFlag==1) {
              this.setData({
                isaddshow:false,
                isaddshowto:true,
                consigneeName:res.data.consigneeInfoList[0].consigneeName,
                consigneeMobile:res.data.consigneeInfoList[0].consigneeMobile,
                consigneeAddress:res.data.consigneeInfoList[0].consigneeAddress,
                trafficCost:typeof(res.data.consigneeInfoList[0].trafficCost)!='undefined'?parseInt(res.data.consigneeInfoList[0].trafficCost):0,
              })
            }
            
          }
         

      }
  })

  

  },
  
  //购物车支付
  gocartpay(){
    console.log('3w')
    var t = this;
    if (this.data.consigneeName!=''&& this.data.consigneeMobile!=''&& this.data.consigneeAddress!='') {
      var goodscarid=''
      t.data.goodsSpecs.forEach(element => {
        if(goodscarid==''){
          goodscarid+=''+element.id
        }else{
          goodscarid+=','+element.id
        }
      });
      wx.request({
        url: app.globalData.Interfaceurl + 'savePreOrder',
        method:'POST',
        header: {
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        data:{
            userId:app.globalData.userId,
            goodsCarIds:goodscarid,
            token:t.data.token,
            orderRemarks:t.data.beizu,
            couponId:t.data.couponId,
            consigneeName:t.data.consigneeName,
            consigneeMobile:t.data.consigneeMobile,
            consigneeAddress:t.data.consigneeAddress,
            trafficCost:t.data.trafficCost
            
        },
        success(res){

          // console.log(res)
          if(res.data.result=='0'){
            wx.requestPayment({
              timeStamp: res.data.dataInfo.timeStamp,
              nonceStr: res.data.dataInfo.nonceStr,
              package: res.data.dataInfo.package,
              signType: res.data.dataInfo.signType,
              paySign: res.data.dataInfo.sign,
              success(res) { 
                console.log(res)
                  wx.switchTab({
                      url: '/pages/index/index',
                  })
              },
              fail(res) {
                  console.log(res)
                  wx.redirectTo({
                    url: '/pages/order/order?showtype=2',
                })
              }
          })

          }else{

            wx.showToast({
              title: res.data.message,
              icon:'none'
            })

          }
            
        }
    })
 
    }else{
      wx.showToast({
        title: '请选择收货地址',
        icon:'none'
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

//     prevPage.setData({
//       consigneeName:e.currentTarget.dataset.consigneename,
//       consigneeMobile:e.currentTarget.dataset.consigneemobile,
//       consigneeAddress:e.currentTarget.dataset.consigneeprovince+''+
//       e.currentTarget.dataset.consigneecity+""+e.currentTarget.dataset.consigneearea+""
//       +e.currentTarget.dataset.consigneeaddress
//         })

    let pages = getCurrentPages();

        let currPage = pages[pages.length - 1];

        console.log(this.data.consigneeName)    //在这里已经发生改变了
        console.log(this.data.consigneeMobile)
        console.log(this.data.trafficCost)
        console.log(this.data.consigneeAddress)
        console.log(this.data.couponId)
        console.log(this.data.couponAmount)
        if (this.data.consigneeName!=''&& this.data.consigneeMobile!=''&& this.data.consigneeAddress!='') {
          this.setData({
            isaddshow:false,
            isaddshowto:true

          })
        }


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})